import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { select, Store } from '@ngrx/store';
import { NzMessageService } from 'ng-zorro-antd';
import { SearchService } from '@services/search.service';
import { getCurrentTimeStamp, isEmptyObject } from '@utils/tool';
import { codeJson, deleteAllCookies } from '@utils/base64';
import { interval, Observable, Subscription } from 'rxjs';
import { filter, map, mergeMap, takeUntil } from 'rxjs/internal/operators';
import { AppStoreModule } from '@store/index';
import { BatchActionsService } from '@store/batch-actions.service';
import { ModalTypes, ShareInfo } from '@store/reducers/member.reducer';
import { SearchResult, SongSheet } from '@services/data-types/common.type';
import { User } from '@services/data-types/member.type';
import { LikeSongParams, MemberService, ShareParams } from '@services/member.service';
import { StorageService } from '@services/storage.service';
import { LoginParams } from '@share/wyy-ui/wyy-layer/wyy-layer-login/wyy-layer-login.component';
import { getMember, getLikedId, getModalType, getModalVisible, getShareInfo } from '@store/selectors/member.selector';

// 扫码成功状态
export const SUCCESS_CODE = 803;
// menu类型
interface Menu {
  label: string;
  readonly path: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent implements OnInit {
  menus: Menu[] = [
    {
      label: '发现',
      path: '/home'
    },
    {

      label: '歌单',
      path: '/sheet'
    }
  ];
  user: User;
  likedId: string;
  // 二维码图片
  qrCodeImg = null;
  timer$: Subscription;
  searchResult: SearchResult;
  wyyLoginParams: LoginParams;
  userSheets: SongSheet[];
  shareInfo: ShareInfo;
  // 登录loading
  showSpin = false;
  // 弹窗显示
  modalVisible = false;
  // 弹窗类型
  currentModalType = ModalTypes.Default;
  loadPercent = 0;
  routeTitle = '';
  private navEnd: Observable<NavigationEnd>;
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private store$: Store<AppStoreModule>,
    private searchService: SearchService,
    private memberService: MemberService,
    private messageService: NzMessageService,
    private storageService: StorageService,
    private titleService: Title,
    private batchActionsService: BatchActionsService
  ) {
    this.router.events.pipe(filter(ev => ev instanceof NavigationEnd)).subscribe(() => {
      this.loadPercent = 0;
      this.setTitle();
    });
    this.navEnd = this.router.events.pipe(filter(evt => evt instanceof NavigationEnd)) as Observable<NavigationEnd>;
    this.setProgressbar();
    this.listenState();
  }
  ngOnInit() {
    this.getUserInfo();
  }
  // 搜索结果处理
  searchKeyWords(keywords: string) {
    if (!keywords.length) {
      this.searchResult = {};
      return;
    }
    this.searchService.getSearchResult(keywords).subscribe(res => {
      this.searchResult = this.highLightKeyword(keywords, res);
      // console.log('searchResult:', this.searchResult);
    });
  }
  // 注册账号
  RegisterAccount(phone: string) {
    this.alertMessage('success', phone + '注册成功');
    this.openModal('loginByPhone');
  }
  // 取消分享
  cancelShare() {
    this.batchActionsService.controlModalVisible(false);
  }
  // 用户登录
  userLogin(params: LoginParams) {
    this.showSpin = true;
    this.memberService.login(params).subscribe(res => {
      this.user = res;
      this.batchActionsService.controlModalVisible(false);
      this.batchActionsService.setUserId(res.profile.userId.toString());
      this.storageService.setStorage({
        key: 'wyyUserId',
        value: res.profile.userId.toString()
      });
      this.alertMessage('success', '登录成功');
      if (params.remember) {
        this.wyyLoginParams = params;
        // 对登录参数进行加密
        this.storageService.setStorage({
          key: 'wyyRem',
          value: JSON.stringify(codeJson(params))
        });
      } else {
        this.storageService.clearStorage('wyyRem');
      }
      this.showSpin = false;
    }, (error) => {
      this.alertMessage('error', error.message || '登录失败');
      this.showSpin = false;
    });
  }
  // 退出登录
  onLogout() {
    this.memberService.logout().subscribe(() => {
      this.alertMessage('success', '已退出登录');
      this.user = null;
      this.qrCodeImg = null;
      deleteAllCookies();
      this.batchActionsService.setUserId('');
      localStorage.removeItem('wyyUserId');
      this.router.navigate(['/']).then();
    }, (error) => {
      this.alertMessage('error', error.message || '退出失败');
    });
  }
  // 动态更新弹窗类型
  changeModalType(type: string) {
    this.batchActionsService.controlModalVisible(true, type);
    // 二维码登录
    if (type === ModalTypes.Default && this.modalVisible) {
      this.getQrCode();
    } else {
      this.qrCodeImg = null;
      this.clearTimer();
    }
  }
  // 获取当前用户的歌单
  onLoadSheets() {
    if (this.user) {
      const uid = this.user.profile.userId.toString();
      this.memberService.getUserSheets(uid).subscribe(userSheet => {
        this.userSheets = userSheet.self;
        this.batchActionsService.controlModalVisible(true);
      });
    } else {
      this.openModal('default');
    }
  }
  // 收藏歌曲
  onLikeSong(args: LikeSongParams) {
    this.memberService.likeSong(args).subscribe(() => {
      this.batchActionsService.controlModalVisible(false);
      this.alertMessage('success', '收藏成功');
    }, error => {
      this.alertMessage('error', error.msg || '收藏失败');
    });
  }
  // 创建歌单
  createSheet(sheetName: string) {
    this.memberService.createSheet(sheetName).subscribe(pid => {
      const args: LikeSongParams = { pid, tracks: this.likedId };
      this.onLikeSong(args);
    }, error => {
      this.alertMessage('error', error.msg || '操作失败');
    });
  }
  // 分享
  onShare(arg: ShareParams) {
    this.memberService.shareResource(arg).subscribe(() => {
      this.alertMessage('success', '分享成功');
      this.closeModal();
    }, error => {
      this.alertMessage('error', error.msg || '分享失败');
    });
  }
  // 获取当前用户的歌单
  onLoadMySheets() {
    if (this.user) {
      const userId = this.user.profile.userId.toString();
      this.memberService.getUserSheets(userId).subscribe(userSheet => {
        this.userSheets = userSheet.self;
        this.batchActionsService.controlModalVisible(true);
      });
    } else {
      this.openModal('loginByPhone');
    }
  }
  openModal(type: string) {
    this.batchActionsService.controlModalVisible(true, type);
  }
  closeModal() {
    this.batchActionsService.controlModalVisible(false);
  }
  private setTitle() {
    this.navEnd.pipe(
      map(() => this.route),
      map((route: ActivatedRoute) => {
        while (route.firstChild) {
          route = route.firstChild;
        }
        return route;
      }),
      mergeMap(route => route.data)
    ).subscribe(data => {
      this.routeTitle = data.title;
      this.titleService.setTitle(this.routeTitle);
    });
  }
  private setProgressbar() {
    interval(100).pipe(takeUntil(this.navEnd)).subscribe(() => {
      this.loadPercent = Math.max(95, ++this.loadPercent);
    });
    this.navEnd.subscribe(() => {
      this.loadPercent = 100;
    });
  }
  // 监听弹窗状态变化
  private listenState() {
    const appStore$ = this.store$.pipe(select(getMember));
    appStore$.pipe(select(getLikedId)).subscribe(id => this.watchLikeId(id));
    appStore$.pipe(select(getShareInfo)).subscribe(info => this.watchShareInfo(info));
    appStore$.pipe(select(getModalType)).subscribe(type => this.watchModalType(type));
    appStore$.pipe(select(getModalVisible)).subscribe(visible => this.watchModalVisible(visible));
  }
  private watchModalVisible(visible: boolean) {
    if (this.modalVisible !== visible) {
      this.modalVisible = visible;
      if (!visible) {
        this.batchActionsService.changeModalType('loginByPhone');
        this.clearTimer();
      }
    }
  }
  private watchModalType(type: ModalTypes) {
    if (this.currentModalType !== type) {
      if (type === ModalTypes.Like) {
        this.onLoadMySheets();
      }
      this.currentModalType = type;
    }
  }
  private watchLikeId(id: string) {
    if (id) {
      this.likedId = id;
    }
  }
  private watchShareInfo(info: ShareInfo) {
    if (info) {
      if (this.user) {
        this.shareInfo = info;
        this.openModal('share');
      } else {
        this.openModal('loginByPhone');
      }
    }
  }
  private getUserInfo() {
    const userId = this.storageService.getStorage('wyyUserId');
    if (userId) {
      this.batchActionsService.setUserId(userId.toString());
      this.memberService.getUserDetail(userId).subscribe(res => {
        this.user = res;
      });
    }
    const wyyLoginParams = this.storageService.getStorage('wyyRem');
    if (wyyLoginParams) {
      this.wyyLoginParams = JSON.parse(wyyLoginParams);
    }
  }
  // 匹配关键字高亮
  private highLightKeyword(keywords: string, result: SearchResult): SearchResult {
    if (!isEmptyObject(result)) {
      const reg = new RegExp(keywords, 'ig');
      ['artists', 'playlists', 'songs'].forEach(type => {
        if (result[type]) {
          result[type].forEach(item => {
            item.name = item.name.replace(reg, '<span class="highlight">$&</span>');
          });
        }
      });
    }
    return result;
  }
  private alertMessage(type: string, content: string) {
    this.messageService.create(type, content);
  }
  // 获取登录二维码，二维码登录流程：生成key => 根据key生成二维码 => 轮询获取二维码接口状态
  private getQrCode() {
    const timeStamp = getCurrentTimeStamp();
    this.memberService.getQRKey(timeStamp).subscribe(res => {
      const nowStamp = getCurrentTimeStamp();
      this.memberService.getQR(res.unikey, nowStamp).subscribe(response => {
        this.qrCodeImg = response.qrimg;
        if (response.qrimg) {
          // 每间隔3秒就要重新验证二维码的有效性
          this.timer$ = interval(3e3).subscribe(() => {
            const currentTimeStamp = getCurrentTimeStamp();
            this.memberService.checkQR(res.unikey, currentTimeStamp).subscribe(resp => {
              if (resp.code === SUCCESS_CODE) {
                // 完成登录后获取用户账号信息
                this.memberService.getAccountInfo().subscribe(result => {
                  this.user = result;
                  this.batchActionsService.controlModalVisible(false, ModalTypes.LoginByPhone);
                  this.batchActionsService.setUserId(result.profile.userId.toString());
                  this.storageService.setStorage({
                    key: 'wyyUserId',
                    value: result.profile.userId.toString()
                  });
                  this.alertMessage('success', '登录成功');
                  this.clearTimer();
                }, error => {
                  this.alertMessage('error', error.msg || '登录失败');
                });
              }
            });
          });
        }
      });
    });
  }
  private clearTimer() {
    if (this.timer$) {
      this.timer$.unsubscribe();
      this.timer$ = null;
    }
  }
}
